<!DOCTYPE html>
<html lang="zh-Hans-CN">
<head>
  <% include("/include/header3.html",{"title":"上传文件",upload:true}){} %>
</head>
<body>
<div class="layui-fluid" id="app">
  <blockquote v-if="description" class="layui-elem-quote"><div v-html="description"></div></blockquote>
  <div class="layui-card">
    <div class="layui-card-body">
      <t-table ref="tableRef" :columns="columns" :data="table.data" :loading="table.loading" bordered hover resizable>
        <!-- 自定义表头，title值为插槽名称  -->
      <template #action>
            <t-button v-if="ACTION_UPLOAD" @click="onReadFile">
              <template #icon><i class="layui-icon layui-icon-upload text-size-14 mr-10"></i></template>
              选择文件
            </t-button>
            <span class="ml-10">
              <t-button theme="warning" @click="closeBtn.close"><i class="layui-icon mr-5 text-size-14" :class="closeBtn.i"></i>{{closeBtn.t}}</t-button>
            </span>
      </template>
        <template #loading>
          <div class="t-table--loading-message">加载数据中，请稍后...</div>
        </template>
      </t-table>
      <div class="pa-25 pb-15">
        <t-pagination v-model="pager.page" v-model:page-size="pager.limit" :total="pager.total" @change="changePage"></t-pagination>
      </div>
    </div>
  </div>
</div>

<script>
  <%
    /*
     使用上传组件示例
     // 打开上传窗口
     const openUpload = () => {
       openLayer({
       title: "上传文件",
       area: ['1200px', '760px'],
       parent: true,
       content: PATH_URL + "upload",
       data: {
         description: "文件上传说明", // 文件上传说明
         queryUrl: PATH_URL + "list", // 查询文件列表路径
         uploadUrl: PATH_URL + "upload", // 上传文件路径
         query: { // 文件查询参数
           category: "测试",
           applyTo: "cs",
           refNum: "33",
         },
         upData: { // 上传参数
           category: "测试",
           applyTo: "cs",
           refNum: "33",
         },
         baseDir: "devFile", // 上传文件根路径
         dir: "ceshi", // 上传文件路径
         actionUpload: true, // 是否允许上传
         actionDown: true, // 是否允许下载
         actionDelete: true, // 是否允许删除
         types: ['jpg'], // 允许上传的文件类型
         multiple: true, // 是否多文件上传
         maxSize: 0, // 文件最大大小，0不限制
         success: () => fetchData(), // 上传文件成功后回调方法
         remove: () => fetchData(), //  删除文件后回调方法
         },
       });
     }
     */
  %>
  const PATH_URL = "dev/file/";
</script>
<script>

  setupVue("#app", {
    setup() {

      const LAYER_DATA = getLayerData();
      if (!LAYER_DATA) {
        console.error("不允许没有参数");
        throw "不允许没有参数";
      }

      const description = LAYER_DATA.description; // 上传说明
      const ACTION_UPLOAD = LAYER_DATA['actionUpload'] || false; // 允许上传
      const ACTION_DELETE = LAYER_DATA['actionDelete'] || false; // 允许删除
      const ACTION_DOWN = LAYER_DATA['actionDown'] || false; // 允许下载

      const QUERY_URL = LAYER_DATA['queryUrl'] || PATH_URL + "list";
      const UPLOAD_URL = LAYER_DATA['uploadUrl'] || PATH_URL + "upload";
      const DELETE_URL = LAYER_DATA['deleteUrl'] || PATH_URL + "delete";

      const pager = Vue.reactive({ page: 1, limit: 10, total: 0 });
      // 参数参数
      const queryForm = LAYER_DATA.query;
      queryForm['columnField'] = "id,name,size_kb,size_info,update_time";

      // 表格相关
      const tableRef = Vue.ref();
      const table = useTable();
      const columns = [
        { colKey: 'serial-number', align: 'center', title: '序', width: "40px" },
        { colKey: 'name', title: '名称', align: 'center', width: "160px", ellipsis: true },
        {
          colKey: 'sizeKb', title: '文件大小', align: 'center', width: "80px", cell: (h, { row }) => {
            return h(TDesign.Tag, { variant: 'light-outline', theme: 'default' }, row.sizeInfo ? row.sizeInfo : renderFileSize(row.sizeKb))
          },
        },
        { colKey: 'updateTime', title: '上传时间', align: 'center', width: "100px" },
        {
          colKey: 'status', title: '状态', align: 'center', width: "60px", cell: (h, { row }) => {
            return h(TDesign.Tag, { variant: 'light-outline', theme: uploadStatus(row) }, uploadText(row))
          },
        },
        {
          colKey: 'id', title: 'action', align: 'center', width: "120px", cell: (h, { row }) => {
            return h(TDesign.Space, {}, [
              ACTION_DOWN && row.status === 'success' ? h(TDesign.Link, { theme: 'primary', onClick: () => onDownload(row.id) }, '下载')
                : ['error', 'canceled'].includes(row.status) ? h(TDesign.Link, { theme: 'primary', onClick: () => startUpload(row) }, '重传') : null,
              ACTION_DELETE && ['error', 'canceled', 'success'].includes(row.status) ? h(TDesign.Link, { theme: 'danger', onClick: () => clickDelete(row) }, '删除')
                : ['uploading'].includes(row.status) ? h(TDesign.Link, { theme: 'danger', onClick: () => cancelUpload(row) }, '取消上传') : null,
            ]);
          },
        },
      ];

      // 内文件列表
      const inFileList = [];
      const fetchData = () => req(axiosGet, QUERY_URL, queryForm, (res) => {
        if (res.code === 200) {
          pager.total = res.data.length;
          res.data.forEach(item => {
            inFileList.push({
              id: item.id,
              uid: item.id,
              name: item.name,
              sizeKb: item.sizeKb,
              sizeInfo: item.sizeInfo,
              updateTime: item.updateTime,
              status: "success",
              percentage: 100,
            })
          })
          buildPage();
        }
      }, table.loading);
      init(() => fetchData());

      // 构建分页
      const buildPage = () => {
        pager.total = inFileList.length;
        let offset = (pager.page - 1) * pager.limit; // 当前页条数
        table.data = offset + pager.limit >= pager.total ?
          inFileList.slice(offset) : inFileList.slice(offset, offset + pager.limit);
      }
      const changePage = () => {
        Vue.nextTick(() => buildPage());
      }

      // 读取文件
      const onReadFile = async () => {
        const multiple = LAYER_DATA['multiple'] || false; // 多文件
        const types = LAYER_DATA['types'] || []; // 上传文件类型
        const maxSize = LAYER_DATA['maxSize'] || 0; // 文件大小
        readFile({ multiple, types, maxSize }).then((res) => {
          const { files } = res;
          for (const file of files) {
            inFileList.unshift({
              uid: file.lastModified,
              name: file.name,
              sizeKb: file.size,
              sizeInfo: null,
              updateTime: null,
              percentage: 0,
              status: "ready",
              file: file,
            });
            buildPage();
            startUpload(table.data[0]);
          }
        });
      };

      // 上传取消列表
      const UPLOAD_CANCEL = [];
      // 开始上传
      const startUpload = (row) => {
        const formData = new FormData();
        const upData = LAYER_DATA['upData']; // 上传参数
        if (upData) {
          Object.keys(upData).map(key => formData.append(key, upData[key]));
        }
        formData.append("file", row.file);
        uploading(UPLOAD_URL, row, formData, (res => {
          const index = UPLOAD_CANCEL.findIndex(item => item.uid === row.uid);
          if (index > -1) UPLOAD_CANCEL.splice(index, 1)
          if (res.code === 200) {
            row.id = res.data.id;
            row.updateTime = res.data.updateTime;
            row.sizeInfo = res.data.sizeInfo;
            if (LAYER_DATA.success) LAYER_DATA.success(res.data);
          } else {
            if (res.msg === 'canceled') {
              row.status = "canceled";
            } else {
              $baseAlert(res.msg);
            }
          }
        }), function (cancel) {
          UPLOAD_CANCEL.push({ uid: row.uid, cancel });
        });
      }

      // 取消上传
      const cancelUpload = (row) => {
        const obj = UPLOAD_CANCEL.find((item) => item.uid === row.uid);
        obj && obj.cancel && obj.cancel();
      };

      // 删除
      const clickDelete = (row) => {
        if (row.status === 'success') {
          handleDelete(axiosDelete, DELETE_URL, { id: row.id }, table, "确定删除【" + row.name + "】文件吗？", () => {
            removeTemp(row);
            if (queryForm.category) row.category = queryForm.category;
            if (LAYER_DATA.remove) LAYER_DATA.remove(row);
          });
        } else {
          removeTemp(row);
        }
      };
      // 删除临时文件
      const removeTemp = (row) => {
        const index = inFileList.findIndex((item) => row.uid === item.uid);
        if (index > -1) {
          inFileList.splice(index, 1);
        }
        buildPage();
      };
      // 下載
      const onDownload = (id) => window.open(BASEURL + PATH_URL + "/download?id=" + id)

      const closeBtn = useCloseBtn();
      return {
        closeBtn,
        tableRef, table, columns, pager, changePage,
        ACTION_UPLOAD, description,
        onReadFile,
      }
    },
  });
</script>


</body>
</html>
